package imgshare.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import imgshare.common.api.CommonResult;
import imgshare.model.User;
import imgshare.model.vo.LoginForm;
import imgshare.model.vo.UserInfo;
import imgshare.service.UserService;
import imgshare.util.JWTUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

import static com.google.common.base.Verify.verify;
import static com.google.common.base.Verify.verifyNotNull;

@RestController
public class AccountController {

    private final static Log log = LogFactory.get();
    @Autowired
    private UserService userService;
    @Autowired
    private JWTUtil jwtUtil;

    @PostMapping("/login")
    public CommonResult<UserInfo> login(@Validated @RequestBody LoginForm loginForm,  HttpServletResponse response) {

        User foundedUser = userService.findByUsername(loginForm.getUsername());
        verifyNotNull(foundedUser,"用户不存在");
        boolean passwordMatch = BCrypt.checkpw(loginForm.getPassword(), foundedUser.getPassword());
        verify(passwordMatch,"密码错误");

        String token = jwtUtil.createToken(foundedUser.getId() + "");
        log.info("为用户[id:{}]生成token[{}]",foundedUser.getId(),token);

        response.setHeader("Authorization",token);
        response.setHeader("Access-control-Expose-Headers", "Authorization");

        UserInfo userInfo = new UserInfo();
        BeanUtil.copyProperties(foundedUser,userInfo);
        log.info("{}成功登陆",loginForm.getUsername());

        return CommonResult.success(userInfo);
    }

    @RequiresAuthentication
    @GetMapping("/logout")
    public CommonResult<?> logout() {
        SecurityUtils.getSubject().logout();
        return CommonResult.success("退出登录成功");
    }

    @PostMapping("/register")
    public CommonResult<?> register(@Validated @RequestBody User user) {

        boolean userExists = userService.existByUsername(user.getUsername());
        verify(!userExists,"用户名已存在");
        userExists = userService.existByEmail(user.getEmail());
        verify(!userExists,"邮箱已存在");

        if (StrUtil.isBlank(user.getNickname())) {
            user.setNickname(user.getUsername());
        }
        // BCrypt加密
        user.setPassword(BCrypt.hashpw(user.getPassword()));
        //todo
        user.setAvatar("https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg");
        LocalDateTime now = LocalDateTime.now();
        user.setCreatedTime(now);
        user.setUpdatedTime(now);
        user.setLastLoginTime(now);
        userService.createUser(user);

        log.info("{}账号创建成功",user.getUsername());
        return CommonResult.success( "账号创建成功");
    }
}
